package com.wrx.club_management_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.entity.ConsumptionItem;
import com.wrx.club_management_backend.service.ConsumptionItemService;
import io.lettuce.core.internal.LettuceClassUtils;
import javafx.scene.AmbientLight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.lang.annotation.Target;
import java.util.List;

@RestController
@RequestMapping("/consumption")
public class ConsumptionItemController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ConsumptionItemService consumptionItemService;

    // 根据活动id 查询消费项
    @PostMapping("/listByActivityId/{activityId}")
    public AjaxResult listByActivityId(@PathVariable("activityId") Long activityId) {
        List<ConsumptionItem> list = consumptionItemService.list(
                new LambdaQueryWrapper<ConsumptionItem>()
                        .eq(ConsumptionItem::getActivityId, activityId)
        );
        return AjaxResult.success(list);
    }

    // 根据社团id 查询消费项
    @PostMapping("/listByClubId/{clubId}")
    public AjaxResult listByClubId(@PathVariable("clubId") Long clubId) {
        List<ConsumptionItem> list = consumptionItemService.list(
                new LambdaQueryWrapper<ConsumptionItem>()
                        .eq(ConsumptionItem::getClubId, clubId)
        );
        return AjaxResult.success(list);
    }

    // 给活动添加消费项
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ConsumptionItem item) {
        item.setStat(1);
        boolean save = consumptionItemService.save(item);
        if (save) return AjaxResult.success("添加成功");
        else return AjaxResult.error("添加失败");
    }

    //支付消费项
    @PostMapping("/pay/{id}")
    public AjaxResult pay(@PathVariable("id") Long id) {
        boolean update = consumptionItemService.update(
                new LambdaUpdateWrapper<ConsumptionItem>()
                        .set(ConsumptionItem::getStat, 2)
        );
        return AjaxResult.success("支付成功");
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody ConsumptionItem item){
        boolean update = consumptionItemService.update(
                new LambdaUpdateWrapper<ConsumptionItem>()
                        .set(ConsumptionItem::getImage, item.getImage())
                        .set(ConsumptionItem::getStat, 3)
                        .eq(ConsumptionItem::getId, item.getId())
        );
        return update ? AjaxResult.success("上传成功") : AjaxResult.error("上传失败");
    }

//    // 给消费项上传发票
//    @PostMapping("/uploadInvoice/{url}/{id}")
//    public AjaxResult uploadInvoice(@PathVariable("url") String url, @PathVariable("id") Long id) {
//        boolean updated = consumptionItemService.update(
//                new LambdaUpdateWrapper<ConsumptionItem>()
//                        .set(ConsumptionItem::getImage, url)
//                        .set(ConsumptionItem::getStat, 3)
//                        .eq(ConsumptionItem::getId, id)
//        );
//        return updated ? AjaxResult.success("上传成功") : AjaxResult.error("上传失败");
//    }

    @PostMapping("/settle")
    public AjaxResult settle(@RequestBody ConsumptionItem item) {
        int tags = item.getTags();
        Long clubId = item.getClubId();
        String key = "club:fund:" + clubId;
//        stringRedisTemplate.opsForHash().increment(key, tags, item.getAmount() * -1);
        //1。 先获取当前该款项的余额
        Object o = stringRedisTemplate.opsForHash().get(key, String.valueOf(tags));
        Long surplus = 0L;
        if (o != null) surplus = Long.parseLong((String) o);
        Long amount = item.getAmount(); // 需要扣除的金额
        if (surplus < amount) return AjaxResult.error("金额不足");
        surplus -= amount;
        boolean update = false;
        synchronized (item.getId()) { // 给该业务上锁
            stringRedisTemplate.opsForHash().put(key, String.valueOf(tags), surplus.toString());
            // 修改item的状态
            update = consumptionItemService.update(
                    new LambdaUpdateWrapper<ConsumptionItem>()
                            .set(ConsumptionItem::getStat, 2)
                            .eq(ConsumptionItem::getId, item.getId())
            );
        }
        if (update) return AjaxResult.success("结算成功");
        else return AjaxResult.error("结算失败");
    }


}
